﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using eTMS.Controllers.TinhThanhService;
using eTMS.Controllers;
using eTMS.Commons;
namespace eTMS.Forms.ManageList{
    public partial class FrmTinhThanh : eTMS.Controls.BaseForm
    {
        public FrmTinhThanh()
        {
            InitializeComponent();
        }
        #region Variables
        private TinhThanhController controller = new TinhThanhController();
        #endregion
        #region Screen Functions
        //Load All lable text
        private void LoadLanguage(){
			this.Text=TinhThanhStringMapping.TinhThanh;
			this.labelFormTitle.Text=Constants.APP_ADMINISTRATION+" "+TinhThanhStringMapping.TinhThanh;
			this.groupBoxDetail.Text=Constants.APP_DETAIL;
			this.groupBoxList.Text=Constants.APP_LIST;
			this.ColumnSTT.HeaderText=Constants.APP_INDEX;
			labelMaTinhThanh.Text=TinhThanhStringMapping.MaTinhThanh;
			ColumnMaTinhThanh.HeaderText=TinhThanhStringMapping.MaTinhThanh;
			labelTenTinhThanh.Text=TinhThanhStringMapping.TenTinhThanh;
			ColumnTenTinhThanh.HeaderText=TinhThanhStringMapping.TenTinhThanh;
			labelGhiChu.Text=TinhThanhStringMapping.GhiChu;
			ColumnGhiChu.HeaderText=TinhThanhStringMapping.GhiChu;
			labelQuocGia_ID.Text=TinhThanhStringMapping.QuocGia_ID;
		    //Search
		    this.groupBoxFilter.Text=Constants.APP_SEARCH;
			cbkMaTinhThanhFilterExact.Text=Constants.APP_SEARCH_EXACT;
			labelMaTinhThanhFilter.Text=TinhThanhStringMapping.MaTinhThanh;
			cbkTenTinhThanhFilterExact.Text=Constants.APP_SEARCH_EXACT;
			labelTenTinhThanhFilter.Text=TinhThanhStringMapping.TenTinhThanh;
			cbkGhiChuFilterExact.Text=Constants.APP_SEARCH_EXACT;
			labelGhiChuFilter.Text=TinhThanhStringMapping.GhiChu;
			labelQuocGia_IDFilter.Text=TinhThanhStringMapping.QuocGia_ID;
		    //end
        }
        //Get entity selected from datagrid
        private TinhThanhEntity GetObject(){
		    TinhThanhEntity o=controller.MapDataRowToObject(((DataRowView)gridData.SelectedRows[0].DataBoundItem).Row);
		    return o;
        }        
        //Get entites selected from datagrid
        private List<DataRow> GetSelectedDataRows(){
		    List<DataRow> ls=new List<DataRow>();
            for(int i=0;i<gridData.SelectedRows.Count;i++){
                ls.Add(GetDataRow(gridData.SelectedRows[i].Index));
            }
		    return ls;
        }
        //Get the selected data row in datagrid
        private DataRow GetSelectedDataRow(){
			DataRow row=GetDataRow(gridData.SelectedRows[0].Index);
		    return row;
        }
         //Get the selected data row in datagrid
        private DataRow GetDataRow(int index){
			DataRow row=((DataRowView)gridData.Rows[index].DataBoundItem).Row;
		    return row;
        }
        //Reset all textbox
        private void ClearScreen(){
			txtMaTinhThanh.Text="";
			txtTenTinhThanh.Text="";
			txtGhiChu.Text="";
			errorProviderData.Clear();
        }
        //Lock-Unlock control in screen
        private void LockScreen(bool IsLocked){            
            ucCommand.LockControl(IsLocked);
			txtMaTinhThanh.ReadOnly = IsLocked;
			txtTenTinhThanh.ReadOnly = IsLocked;
			txtGhiChu.ReadOnly = IsLocked;
			txtQuocGia_ID.ReadOnly = IsLocked;
        }
        //Copy data from control in screen to object
        private void CopyFromSreen(TinhThanhEntity o){
			 o.MaTinhThanh=Convert.ToString(txtMaTinhThanh.Text);
			 o.TenTinhThanh=Convert.ToString(txtTenTinhThanh.Text);
			 o.GhiChu=Convert.ToString(txtGhiChu.Text);
			 o.QuocGia_ID=Convert.ToInt32(txtQuocGia_ID.SelectedValue);
        }
        //Bind data from object to control in screen
        private void CopyToSreen(TinhThanhEntity o){
		    if(!o.IsNullMaTinhThanh){
			txtMaTinhThanh.Text=Convert.ToString(o.MaTinhThanh);
		    }
		    if(!o.IsNullTenTinhThanh){
			txtTenTinhThanh.Text=Convert.ToString(o.TenTinhThanh);
		    }
		    if(!o.IsNullGhiChu){
			txtGhiChu.Text=Convert.ToString(o.GhiChu);
		    }
            if(!o.IsNullQuocGia_ID){
				txtQuocGia_ID.SelectedValue=o.QuocGia_ID;
			}
			else{
				txtQuocGia_ID.SelectedValue=null;
			}
        }
        //Validate all data from control in screen before Save data
        protected bool ValidateScreen(){
		    bool result=true;
			if(txtMaTinhThanh.Text.Trim()==""){
				txtMaTinhThanh.Focus();
				errorProviderData.SetError (txtMaTinhThanh, Constants.MSS_ERROR_TEXT);
				result=false;
			}			
			else{
				errorProviderData.SetError(txtMaTinhThanh, "");
			}			
			if(txtTenTinhThanh.Text.Trim()==""){
				txtTenTinhThanh.Focus();
				errorProviderData.SetError (txtTenTinhThanh, Constants.MSS_ERROR_TEXT);
				result=false;
			}			
			else{
				errorProviderData.SetError(txtTenTinhThanh, "");
			}			
			if(((txtQuocGia_ID.SelectedIndex<=0)&&((txtQuocGia_ID.IsAddChooseItem)||(txtQuocGia_ID.IsAddAllItem)))||(txtQuocGia_ID.SelectedIndex<0)){
				txtQuocGia_ID.Focus();
				errorProviderData.SetError(txtQuocGia_ID, Constants.MSS_ERROR_DROPDOWN);
				result=false;
			}
			else{
				errorProviderData.SetError (txtQuocGia_ID, "");
			}
		    if(!result){
				ShowInfo(Constants.MSS_REQUIRE_FIELD);
		    }
		    return result;
        }
        //Copy data from selected object to control in screen
        private void BindInfo(){
			if (gridData.SelectedRows.Count == 0) return;
			if(gridData.SelectedRows[0].Index<gridData.Rows.Count){
				TinhThanhEntity o=GetObject();	
				CopyToSreen(o);
		    }
        }    
        #endregion
        #region Business
        //AddNew data to database
        private bool AddNewData()
        {
			bool rval=false;
            controller.ResetObject();		
		    CopyFromSreen(controller.TinhThanhObject);		    
            rval=controller.AddNew();
            if(rval){
				DataRow row=controller.Table.NewRow();
				row["STT"]=controller.Table.Rows.Count+1;
				controller.MapObjectToDataRow(row);
				controller.Table.Rows.Add(row);
				gridData.DataSource=null;
				gridData.DataSource=controller.Table;
            }
            return rval;
        }
        //Update data to database
        private bool UpdateData()
        {      
			DataRow row=GetSelectedDataRow();
            controller.LoadObject((Int32)row["TinhThanh_ID"]);		
		    CopyFromSreen(controller.TinhThanhObject);
		    bool rval=controller.Update();
            if(rval){
				controller.MapObjectToDataRow(row);
				gridData.InvalidateRow(gridData.SelectedRows[0].Index);
            }
            return rval;
        }
        //Delete data from database
        private bool DeleteData()
        {
            List<DataRow> ls=GetSelectedDataRows();
            if(ls.Count==0)return false;  
            bool rval=true; 
            try{
                gridData.DataSource = null;
				foreach(DataRow row in ls){
					if(controller.DeleteByID((Int32)row["TinhThanh_ID"])){
						 this.controller.Table.Rows.Remove(row);
					}	
					else
					{
						rval=false;
					}				
				}
				this.controller.ResetTableIndex();
                gridData.DataSource = this.controller.Table;
            }
            catch{
				return false;
            }
            return true;
        }        
        #endregion
        #region DataBinding 
        //Bind data to datagrid
        private void LoadData(){
            gridData.AutoGenerateColumns = false;
            gridData.DataSource=controller.Table;     
            gridData.AutoResizeColumns();       
        }
        #endregion
        #region Windows Control EventHandlers
        private void FrmTinhThanh_Load(object sender, EventArgs e)
        {
			LoadLanguage();
            LoadData();
            LockScreen(true);
            this.groupBoxFilter.ToggleCollapsed();
        }       
		private void gridData_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
			BindInfo();
        }   
        private void ucCommand_OnAddNew(object sender, EventArgs e)
        {
			ClearScreen();
            LockScreen(false);
            Flag=ACTIONENUM.AddNew;
			txtMaTinhThanh.Focus();
        }
        private void ucCommand_OnDelete(object sender, EventArgs e)
        {
			if(gridData.SelectedRows.Count==0){
                ShowInfo(Constants.MSS_CHOOSERECORD_REQUIRE);
                return;
            }
            if(!Confirm(Constants.MSS_CONFIRM_DELETE))return;
            DeleteData();
			this.gridData.Focus();
        }
        private void ucCommand_OnEdit(object sender, EventArgs e)
        {
			if(gridData.SelectedRows.Count==0){
                ShowInfo(Constants.MSS_CHOOSERECORD_REQUIRE);
                return;
            }
            LockScreen(false);
            Flag=ACTIONENUM.Edit;
			txtMaTinhThanh.Focus();
        }
        private void ucCommand_OnSave(object sender, EventArgs e)
        {
			if(!ValidateScreen())
				return;
            if(Flag==ACTIONENUM.Edit){
                if(UpdateData()){
                    ShowInfo(Constants.MSS_SAVE_SUCCESS);
                }
                else{
                    ShowWarning(Constants.MSS_SAVE_FAILE);
                }
                gridData.Focus();
            }
            else{
                if(AddNewData()){
                    ShowInfo(Constants.MSS_SAVE_SUCCESS);
                }
                else{
                    ShowWarning(Constants.MSS_SAVE_FAILE);
                }
            }
            LockScreen(true);
            Flag=ACTIONENUM.None;
        }
        private void ucCommand_OnSkip(object sender, EventArgs e)
        {
			LockScreen(true);  
			if(Flag==ACTIONENUM.AddNew){			
				ClearScreen();    
				ucCommand.SetFocusAddNew();
			}
			else if(Flag==ACTIONENUM.Edit){				
				BindInfo();
				this.gridData.Focus();
			}      
            Flag=ACTIONENUM.None;
        }
        #endregion   
        #region Filters
        private string GetFilter(){
			string strFilter="";
			if(txtMaTinhThanhFilter.Text.Trim()!=""){
				if(cbkMaTinhThanhFilterExact.Checked){
					strFilter+=" AND MaTinhThanh='"+txtMaTinhThanhFilter.Text.Trim()+"'";
				}
				else{
					strFilter+=" AND MaTinhThanh LIKE '%"+txtMaTinhThanhFilter.Text.Trim()+"%'";
				}
			}	
			if(txtTenTinhThanhFilter.Text.Trim()!=""){
				if(cbkTenTinhThanhFilterExact.Checked){
					strFilter+=" AND TenTinhThanh='"+txtTenTinhThanhFilter.Text.Trim()+"'";
				}
				else{
					strFilter+=" AND TenTinhThanh LIKE '%"+txtTenTinhThanhFilter.Text.Trim()+"%'";
				}
			}	
			if(txtGhiChuFilter.Text.Trim()!=""){
				if(cbkGhiChuFilterExact.Checked){
					strFilter+=" AND GhiChu='"+txtGhiChuFilter.Text.Trim()+"'";
				}
				else{
					strFilter+=" AND GhiChu LIKE '%"+txtGhiChuFilter.Text.Trim()+"%'";
				}
			}	
			if(txtQuocGia_IDFilter.SelectedIndex>0){
				strFilter+=" AND QuocGia_ID='"+txtQuocGia_IDFilter.SelectedValue.ToString()+"'";	
			}
			if(strFilter.Length>0)
				strFilter=strFilter.Substring(4);
			return strFilter;
		}
		private void FilterData(){		
            gridData.ClearSelection();
			controller.Table.DefaultView.RowFilter=GetFilter();
		}
        private void btnSearch_Click(object sender, EventArgs e)
        {
			FilterData();
        }
        #endregion   
    }
}
